import { modelListTenant } from "@/services/languageModel";
import { formatMessage } from 'umi-plugin-react/locale';
import { Button, Card, Col, Divider, Form,Icon,Input, Row, Select,InputNumber, message,Drawer, DatePicker, Dropdown, Menu, Tag, Switch } from "antd";
import React from "react";
import testData from "../resourceManage/testData";
import { packageAdd, packageDetail, packageUpdate, resourceOptionList } from "@/services/chargingManage";
import moment from "moment";

class PackageReadonly extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      readOnly:false,
      modelOriginList:[],
      modelList:[],
      customOriginList:[],
      customList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  getLlmList = async () => {
    const res = await resourceOptionList({resourceType:15})
    
    this.setState({modelOriginList:res})
  }

  getCustomList = async () => {
    const res = await resourceOptionList({resourceType:16})
    
    this.setState({customOriginList:res})
  }

  initModal = (row,readOnly) => {
    this.setState({
      visible:true,
      id:row?.id,
      readOnly
    },() => {
      this.getLlmList()
      this.getCustomList()
      if(row){
        this.getInfo()
      }
    })
  }

  getInfo = async () => {
    const res = await packageDetail({id:this.state.id})
    console.log(res);
    const { form:{setFieldsValue} } = this.props;
    
    setFieldsValue({
      name:res.name
    })

    //处理资源
    const modelList = []
    const customList = []
    for(const item of res.detailList){
      if(item.resourceType == 15){
        //模型
        modelList.push({
          id:item.resourceId,
          resourceName:item.resourceName
        })
        this.setState({modelList},() => {
          setFieldsValue({...this.returnFieldByInfo(item.resourceId,item)})
        })
      }else if(item.resourceType == 16){
        //自定义资源
        customList.push({
          id:item.resourceId,
          resourceName:item.resourceName
        })
      }else{    
        setFieldsValue({...this.returnFieldByInfo(item.resourceType,item)})
      }
    }

    this.setState({customList})
    
  }

  onClose = () => {
    this.setState({
      visible:false,
      id:null,
      readOnly:false
    })
  }

  renderNumberBox = (getFieldValue,getFieldDecorator,param) => (
    <div style={{display:'flex',alignItems:"center",gap:'8px'}}>      
      <Form.Item style={{marginBottom:0}}>
        {getFieldDecorator(param.fieldPrefix+'_isLimit',{initialValue:1})(
          <Select style={{width:80}} disabled={this.state.readOnly}>
            <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.limited' })}</Select.Option>
          <Select.Option value={0}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.unlimited' })}</Select.Option>
          </Select>
        )}
      </Form.Item>
      {
        getFieldValue(param.fieldPrefix+'_isLimit') == 1 ? (
          <>
            <span>{param.isEveryOne ? formatMessage({ id: 'chargingManage.packageManage.packageReadonly.each' }) : formatMessage({ id: 'chargingManage.packageManage.packageReadonly.totalAmount' })}</span>
            {
              param.isEveryOne ? (
                <Form.Item style={{marginBottom:0}}>
                  {getFieldDecorator(param.fieldPrefix+'_timeLimit',{initialValue:1})(
                    <Select disabled={this.state.readOnly}>
                      <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.month' })}</Select.Option>
          <Select.Option value={2}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.year' })}</Select.Option>
                    </Select>
                  )}
                </Form.Item>
              ) : ''
            }
            <Form.Item style={{marginBottom:0}}>
              {getFieldDecorator(param.fieldPrefix+'_num')(
                <InputNumber min={0} precision={0} disabled={this.state.readOnly} />
              )}
            </Form.Item>
            <span>{param.unitText}</span>

            <Divider type="vertical" style={{height:32}} />

            <span>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.upperLimit' })}</span>
            <Form.Item style={{marginBottom:0}}>
              {getFieldDecorator(param.fieldPrefix+'_maxNum')(
                <InputNumber min={0} precision={0} disabled={this.state.readOnly} />
              )}
            </Form.Item>
            <span>{param.unitText}</span>
            <Form.Item style={{marginBottom:0}}>
              {getFieldDecorator(param.fieldPrefix+'_numOverflow',{initialValue:1})(
                <Select style={{width:200}} disabled={this.state.readOnly}>
                  <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.overflowAllowed' })}</Select.Option>
          <Select.Option value={0}>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.overflowNotAllowed' })}</Select.Option>
                </Select>
              )}
            </Form.Item>
          </>
        ) : ''
      }
    </div>
  )

  renderHourBox = (getFieldValue,getFieldDecorator,param) => (
      <div style={{display:'flex',alignItems:"center",gap:'8px'}}>
        <Form.Item style={{marginBottom:0}}>
          {getFieldDecorator(param.fieldPrefix+'_isLimit',{initialValue:1})(
              <Select style={{width:80}} disabled={this.state.readOnly}>
                <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.limited' })}</Select.Option>
                <Select.Option value={0}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.unlimited' })}</Select.Option>
              </Select>
          )}
        </Form.Item>
        {
          getFieldValue(param.fieldPrefix+'_isLimit') == 1 ? (
              <>
                <span>{param.isEveryOne ? formatMessage({ id: 'chargingManage.packageManage.packageReadonly.each' }) : formatMessage({ id: 'chargingManage.packageManage.packageReadonly.totalDuration' })}</span>
                {
                  param.isEveryOne ? (
                      <Form.Item style={{marginBottom:0}}>
                        {getFieldDecorator(param.fieldPrefix+'_timeLimit',{initialValue:1})(
                            <Select disabled={this.state.readOnly}>
                              <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.month' })}</Select.Option>
                              <Select.Option value={2}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.year' })}</Select.Option>
                            </Select>
                        )}
                      </Form.Item>
                  ) : ''
                }
                <Form.Item style={{marginBottom:0}}>
                  {getFieldDecorator(param.fieldPrefix+'_num',{rules: [{ required: true, message: formatMessage({ id: 'chargingManage.packageManage.packageReadonly.pleaseInput' }) }]})(
                      <InputNumber min={0} precision={0} disabled={this.state.readOnly} />
                  )}
                </Form.Item>
                <span>{param.unitText}</span>

                <Divider type="vertical" style={{height:32}} />

                <span>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.upperLimit' })}</span>
                <Form.Item style={{marginBottom:0}}>
                  {getFieldDecorator(param.fieldPrefix+'_maxNum',{rules: [{ required: true, message: formatMessage({ id: 'chargingManage.packageManage.packageReadonly.pleaseInput' }) }]})(
                      <InputNumber min={0} precision={0} disabled={this.state.readOnly} />
                  )}
                </Form.Item>
                <span>{param.unitText}</span>
                <Form.Item style={{marginBottom:0}}>
                  {getFieldDecorator(param.fieldPrefix+'_numOverflow',{initialValue:1,rules: [{ required: true, message: formatMessage({ id: 'chargingManage.packageManage.packageReadonly.pleaseInput' }) }]})(
                      <Select style={{width:200}} disabled={this.state.readOnly}>
                        <Select.Option value={1}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.overflowAllowed' })}</Select.Option>
                        <Select.Option value={0}>{formatMessage({ id: 'chargingManage.packageManage.packageDrawer.overflowNotAllowed' })}</Select.Option>
                      </Select>
                  )}
                </Form.Item>
              </>
          ) : ''
        }
      </div>
  )

  validateForm = () => {
    this.props.form.validateFields((error,values) => {
      console.log(values);
      
      if(!error){
        const { modelList,customList } = this.state;
        let obj = {}
        let detailList = []
        for(const key in values){
          if(key.indexOf("_") == -1){
            obj[key] = key== 'enableDate' || key =='disableDate' ? moment(values[key]).format("YYYY-MM-DD") :  values[key]
          }
        }

        //固定资源
        for(let i = 0;i<15;i++){
          detailList.push({
            ...this.returnField(i,values),
            resourceType:i,
          })
        }

        //模型资源
        for(const item of modelList){
          detailList.push({
            ...this.returnField(item.id,values),
            resourceType:15,
            resourceName:item.resourceName,
            resourceId:item.id
          })
        }

        //自定义资源
        for(const item of customList){
          detailList.push({
            ...this.returnField(item.id,values),
            resourceType:16,
            resourceName:item.resourceName,
            resourceId:item.id
          })
        }

        obj.detailList = detailList

        this.doSubmit(obj)
        
      }
    })
  }

  doSubmit = async obj => {
    let res = {}
    if(this.state.id){
      obj.id = this.state.id
      res = await packageUpdate(obj)
    }else{
      res = await packageAdd(obj)
    }
    message.info(res.message)
    this.onClose()
    this.props.refreshList()
  }

  addModel = item => {
    const { modelList } = this.state;
    modelList.push(item)
    this.setState({modelList})
  }

  removeModel = id => {
    const { modelList } = this.state;
    const newList = modelList.filter(item => item.id != id)
    this.setState({modelList:newList})
  }

  addCustom = item => {
    const { customList } = this.state;
    customList.push(item)
    this.setState({customList})
  }

  removeCustom = id => {
    const { customList } = this.state;
    const newList = customList.filter(item => item.id != id)
    this.setState({customList:newList})
  }

  returnField = (prefix,values) => {
    return {
      isLimit:values[prefix+'_isLimit'],
      timeLimit:values[prefix+'_timeLimit'],
      num:values[prefix+'_num'],
      maxNum:values[prefix+'_maxNum'],
      numOverflow:values[prefix+'_numOverflow'],
    }
  }

  returnFieldByInfo = (prefix,value) => {
    return {
      [prefix+'_isLimit']:value['isLimit'],
      [prefix+'_timeLimit']:value['timeLimit'],
      [prefix+'_num']:value['num'],
      [prefix+'_maxNum']:value['maxNum'],
      [prefix+'_numOverflow']:value['numOverflow'],
    }
  }

  render(){
    const { visible,id,readOnly,modelOriginList,modelList,customOriginList,customList } = this.state;
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    };
    const modelIds = modelList.map(item => item.id)
    const customIds = customList.map(item => item.id)
    const menu = (
      <Menu>
        {
          modelOriginList.map(item => {
            return modelIds.indexOf(item.id) === -1 ? (
              <Menu.Item key={item.id} onClick={() => this.addModel(item)}>{item.resourceName}</Menu.Item>
            ) : ''
          })
        }
      </Menu>
    );
    const menu2 = (
      <Menu>
        {
          customOriginList.map(item => {
            return customIds.indexOf(item.id) === -1 ? (
              <Menu.Item key={item.id} onClick={() => this.addCustom(item)}>{item.resourceName}</Menu.Item>
            ) : ''
          })
        }
      </Menu>
    );

    return (
      <Form {...formItemLayout} >
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.packageName' })}>
          {getFieldDecorator('name', {
            rules: [{ required: true, message: formatMessage({ id: 'chargingManage.packageManage.packageReadonly.pleaseInput' }) }],
            getValueFromEvent: event => event.target.value.replace(/\s+/g, '')
          })(<Input autoComplete="off" disabled={this.state.readOnly} />)}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.resources' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.disk' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'0',
            isEveryOne:true,
            unitText:'M'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.usageDuration' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'1',
            isEveryOne:true,
            unitText:'min'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.qaCount' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'2',
            isEveryOne:true,
            unitText:'次'
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.knowledge' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.knowledgePoint' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'3',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.mindMap' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'4',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.document' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'7',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.multipleRounds' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'5',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.model' })}</h3>
        {
          modelList.map(item => {
            return (
              <Form.Item label={item.resourceName} key={item.id} style={{position:"relative"}}>
                {this.renderNumberBox(getFieldValue,getFieldDecorator,{
                  fieldPrefix:item.id,
                  isEveryOne:true,
                  unitText:'token',
                  showRemove:true
                })}
              </Form.Item>
            )
          })
        }

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.serviceProvider' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.companyCount' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'8',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.companyAdmin' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'9',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.userSide' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.userAdmin' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'10',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.user' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'11',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.aiConsultant' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.aiConsultantLabel' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'13',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.workOrder' })}</h3>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.workOrderQuantity' })}>
          {this.renderNumberBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'14',
            isEveryOne:false,
            unitText:'个'
          })}
        </Form.Item>
        <Form.Item label={formatMessage({ id: 'chargingManage.packageManage.packageReadonly.workOrderDuration' })}>
          {this.renderHourBox(getFieldValue,getFieldDecorator,{
            fieldPrefix:'17',
            isEveryOne:false,
            unitText:formatMessage({ id: 'chargingManage.packageManage.packageDrawer.hour' }),
          })}
        </Form.Item>

        <Divider style={{marginTop:0}} />

        <h3>{formatMessage({ id: 'chargingManage.packageManage.packageReadonly.customResource' })}</h3>
        {
          customList && customList.length > 0 ? (
            <Form.Item label=" " colon={false}>
              {
                customList.map(item => {
                  return <Tag style={{marginRight:8}} closable={!this.state.readOnly} onClose={() => this.removeCustom(item.id)} key={item.id}>{item.resourceName}</Tag>
                })
              }
            </Form.Item>
          ) : ''
        }
        
      </Form>
    )
  }
}

export default Form.create()(PackageReadonly)